package bysj.dyz.service;

import bysj.dyz.bean.Page;
import bysj.dyz.bean.User;
import bysj.dyz.dao.UserDao;

import java.sql.SQLException;
import java.util.List;

public class UserService {
    public Page pageselectuser(int currentPage, int currentCount) throws SQLException {
        Page page = new Page();
        UserDao userDao = new UserDao();
        int totalCount = userDao.queryCount();


        /*  总数   每页显示数目  总页数
             9        10    0.9     1
             10       10     1      1
             11       10    1.1     2
            java ceil
         */
        // 2 根据总数和当前页显示数 计算出总页数
        int totalPage= (int) Math.ceil(1.0*totalCount/currentCount);
        //3 将分页相关信息封装到page类中
        page.setCurrentCount(currentCount);
        page.setCurrentPage(currentPage);
        page.setTotalCount(totalCount);
        page.setTotalPage(totalPage);

        // 计算查询的起始位置
//        页数  每页显示条数  起始位置
//
//        1        3           0
//        2        3           3
//        3        3           6  （currentPage-1）*currentCount
        //计算出起始位置
        int startPosition=(currentPage-1)*currentCount;
        // 分页查询数据
        List<User> applies = userDao.pageselectuser( startPosition, currentCount);
        // 将集合数据封装到page类中
        page.setList(applies);



        return page;
    }

    public boolean deleteuser(String userid) throws SQLException {
        UserDao userDao = new UserDao();
        boolean deleteuser = userDao.deleteuser(userid);
        return  deleteuser;
    }

    public boolean register(User user) throws SQLException {


        boolean register=false;
        UserDao userDao=new UserDao();
        boolean checkUser = userDao.checkUser(user.getUsername());
        //如果不存在就保存到数据库
        if (checkUser){
            register = userDao.register(user);

        }

        return  register;
    }
}
